package org.example;

import org.example.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:向表中插入记录
 * User: dings
 * Date: 2024-09-21
 * Time: 15:06
 */
public class Demo03_insert {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtils.getConnection();
            String sql = "insert into student (sn, name, mail, class_id) values (?,?,?,?)";
            statement = connection.prepareStatement(sql);
            Scanner scanner = new Scanner(System.in);

            System.out.println("请输入学号：");
            String sn = scanner.next();

            System.out.println("请输入姓名：");
            String name = scanner.next();

            System.out.println("请输入邮箱：");
            String mail = scanner.next();

            System.out.println("请输入班级编号：");
            Long classId = Long.valueOf(scanner.next());

            //编号从1开始
            statement.setString(1, sn);
            statement.setString(2, name);
            statement.setString(3, mail);
            statement.setLong(4, classId);

            int row = statement.executeUpdate();
            if(row == 1) {
                System.out.println("插入成功！");
            }else {
                System.out.println("插入失败！");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            // 释放资源,关闭连接
            DBUtils.close(null, statement, connection);
        }
    }
}
